package org.lojzes.minstruts.xml;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class XMLParse {
	private static Log log = LogFactory.getLog(XMLParse.class);
    public static Map<String,XMLBean> parse(String path){
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 Map<String, XMLBean> beanMap = new HashMap<String,XMLBean>();
    	 try {
			Document document = saxBuilder.build(new File(path));
			Element root = document.getRootElement();
			Element actionMapping = root.getChild("action-mapping");
			List<Element> actions = actionMapping.getChildren();
			for (Element action : actions) {
				XMLBean xbean = new XMLBean();
				Element formBeans = root.getChild("form-beans");
				List<Element> forms = formBeans.getChildren();
				for (Element form : forms) {
					  if(form.getAttributeValue("name").equals(action.getAttributeValue("name"))){
						  xbean.setBeanName(action.getAttributeValue("name"));
						  xbean.setBeanClass(form.getAttributeValue("class"));
						  break;
					  }
				}
				xbean.setActionType(action.getAttributeValue("type"));
				xbean.setPath(action.getAttributeValue("path"));
				List<Element> forwards = action.getChildren();
				HashMap<String, String> forwardMap = new HashMap<String,String>();
				for (Element forward : forwards) {
					forwardMap.put(forward.getAttributeValue("name"),forward.getAttributeValue("value"));
					xbean.setForwards(forwardMap);
				}
				beanMap.put(xbean.getPath(), xbean);
			}
			log.info("===>>配置文件已经初始化完成!");
			log.info(beanMap.toString());
		} catch (Exception e) {
			log.error("===>>严重："+e);
		}
    	 return beanMap;
    }
    public static void main(String[] args) {
    	Map<String, XMLBean> parse = XMLParse.parse("D:\\eclipseworkspace\\minstruts\\WebContent\\WEB-INF\\minstruts-config.xml");
    	Set<String> keySet = parse.keySet();
    	for (String key : keySet) {
			System.out.println(key);
		    System.out.println(parse.get(key));
		}
	}
}
